package com.ibatis.plugin;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.sql.DataSource;

import com.ibatis.common.jdbc.SimpleDataSource;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.transaction.TransactionConfig;
import com.ibatis.sqlmap.engine.transaction.TransactionException;
import com.ibatis.sqlmap.engine.transaction.TransactionManager;
import com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig;

public class DBManager {

	private static DBManager manager = new DBManager();
	
	private SqlMapClient client;
	
	private DBManager(){
		try {
			client = build();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransactionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static DBManager getInstance(){
		return manager;
	}
	
	public SqlMapClient getSqlMapClient(){
		return client;
	}
	
	private SqlMapClient build() throws IOException, SQLException, TransactionException{
		String resource = "sql-map-config.xml";               
        Reader reader = Resources.getResourceAsReader (resource);                
        SqlMapClientImpl sqlMap = (SqlMapClientImpl) SqlMapClientBuilder.buildSqlMapClient(reader);               
        TransactionConfig transactionConfig = new ExternalTransactionConfig();        
        Properties properties = new Properties();               
        properties.setProperty("SetAutoCommitAllowed", "false");               
        transactionConfig.setDataSource(getDataSource());               
        transactionConfig.setProperties(properties);               
        TransactionManager txManager = new TransactionManager(transactionConfig);               
                       
        sqlMap.getDelegate().setTxManager(txManager);
        return sqlMap;
	}
	
	
	private DataSource getDataSource(){
		Map<String,Properties> prop = new HashMap<String,Properties>();
		
		RoutingDataSource dds = new RoutingDataSource();
		
		for(Entry<String, Properties> entry : prop.entrySet()){
			
			dds.put(entry.getKey(), new SimpleDataSource(entry.getValue()));
		}
		
		return new RoutingDataSource();
	}
}
